<template>
  <div>
    <el-row :gutter="14">
      <el-col :span="4">
        <div class="form_item category">
          <label>分类：</label>
          <div class="inp_content">
            <el-select
              v-model="data.searchData.categoryId"
              placeholder="请选择"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in data.categoryData"
                :key="item.id"
                :label="item.category_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="form_item date">
          <label>日期：&nbsp;&nbsp;&nbsp;</label>
          <div class="inp_content">
            <el-date-picker
              v-model="data.searchData.date"
              type="datetimerange"
              align="center"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="data.pickerOption"
              style="width: 100%"
              clearable
            >
            </el-date-picker>
          </div>
        </div>
      </el-col>
      <el-col :span="3">
        <div class="form_item keyword">
          <label>关键字：&nbsp;&nbsp;</label>
          <div class="inp_content">
            <selectVue :config="data.configOption" :selectData.sync="data.searchData.selectData" />
          </div>
        </div>
      </el-col>
      <el-col :span="3">
        <el-input
          v-model="data.searchData.keywords"
          placeholder="请输入内容"
          style="width: 100%"
          clearable
          autocomplete="off"
        ></el-input>
      </el-col>
      <el-col :span="2">
        <el-button
          type="danger"
          style="height: 40px"
          @click="laodData"
          icon="el-icon-search"
        >搜索
        </el-button>
      </el-col>
      <el-col :span="5">
        <el-tooltip class="item" effect="dark" content="新增" placement="top-start">
          <el-button
            type="primary"
            icon="el-icon-plus"
            circle
            class="pull_right"
            style="width:40px;height: 40px"
            @click="data.addDialogInfo = true"
          ></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 表格数据 -->
    <el-table
      ref="multipleTable"
      :data="data.tableData"
      v-loading="data.loadingData"
      tooltip-effect="dark"
      style="width: 100%"
      :header-cell-style="{background:'#F5F7FA'}"
      class="margin_top_30 margin_bottom_30"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="标题"
        prop="title"
        align="center"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        label="类型"
        prop="categoryId"
        align="center"
        width="130"
        :formatter="toCategory"
      >
      </el-table-column>
      <el-table-column
        label="日期"
        prop="createDate"
        align="center"
        width="235"
        sortable
        :formatter="toDate"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="300"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="deleteItem(scope.row.id)"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="success"
            @click="handleEdit(scope.row.id)"
          >编辑
          </el-button>
          <router-link :to="{
                        name: 'InfoEditDetails',
                        query: { id: scope.row.id }
                    }">
          </router-link>
          <el-button
            size="mini"
            type="primary"
            @click="toDetails(scope.row)"
          >编辑详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row>
      <el-col :span="12">
        <el-button size="small" @click="delectAll">批量删除</el-button>
      </el-col>
      <el-col :span="12">
        <el-pagination
          class="pull_right"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-size="10"
          :current-page="1"
          :page-sizes="[10,20,50,100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total">
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 新增 -->
    <addInfoDialog
      :flag.sync="data.addDialogInfo"
      :category="data.categoryData"
      @getListEmit="laodData"
    />

    <!-- 编辑 -->
    <editInfoDialog
      :flag.sync="data.editDialogInfo"
      :id="data.editInfoID"
      :category="data.categoryData"
      @getListEmit="laodData"
    />
  </div>
</template>

<script>
import { reactive, ref, onMounted, watchEffect } from "@vue/composition-api";
import { global } from "@/utils/global3.0";
import { dateFormat } from "@/utils/common";
import { common } from "@/api/common";
import selectVue from "@c/select";
import addInfoDialog from "./components/addInfoDialog";
import editInfoDialog from "./components/editInfoDialog";
import { GetInfoList, EditInfo, DelectInfo } from "@/api/news";

export default {
  name: "index",
  components: {
    selectVue,
    addInfoDialog, // 新增弹窗
    editInfoDialog // 编辑弹窗
  },
  setup(props, { root }) {
    const { confirm } = global();
    const { GetInfoCategory, categoryItem } = common();
    /**
     * 数据
     */
    const data = reactive({
      // 分类
      categoryData: [],
      configOption: {
        init: ["id", "title"]
      },
      // 搜索
      searchData: {
        categoryId: "",
        date: [],
        selectData: {},
        keywords: ""
      },
      // 新增标识
      addDialogInfo: false,
      // 编辑标识
      editDialogInfo: false,
      editInfoID: "",
      // 表格数据
      tableData: [],
      // 表格loading
      loadingData: false,
      // 总条数
      total: 0,
      // 页码
      pageNum: 1,
      // 页数
      pageSize: 10,
      // 删除信息ID
      deleteInfoID: []
    });
    /**
     * method 方法
     */
      // 获取分类
    const getInfoCategory = () => {
        root.$store.dispatch("common/getInfoCategory", "").then(res => {
          data.categoryData = res;
        });
      };
    // 处理搜索条件
    const formatData = () => {
      let requestData = {
        pageNumber: data.pageNum,
        pageSize: data.pageSize
      };
      // 分类id
      if (data.searchData.categoryId) {
        requestData.categoryId = data.searchData.categoryId;
      }
      // 日期
      if (data.searchData.date.length > 0) {
        requestData.startTiem = data.searchData.date[0];
        requestData.endTime = data.searchData.date[1];
      }
      // 关键字
      if (data.searchData.keywords) {
        requestData[data.searchData.selectData.value] = data.searchData.keywords;
      }
      return requestData;
    };

    // 列表数据
    const laodData = () => {
      data.loadingData = true;
      let requestData = formatData();
      GetInfoList(requestData).then(res => {
        let resData = res.data.data;
        // 更新数据
        data.tableData = resData.data;
        data.total = resData.total;
        data.loadingData = false;
      }).catch(error => {
        data.loadingData = false;
        console.log(error);
      });
    };

    // 转成分类
    const toCategory = (row) => {
      let categoryId = row.categoryId;
      let categoryArr = data.categoryData.filter(item => item.id === categoryId)[0];
      if (!categoryArr) {
        return false;
      }
      return categoryArr.category_name;
    };
    // 转成日期格式
    const toDate = (row) => dateFormat(row.createDate, "Y-M-D H:I:S");

    // 编辑
    const handleEdit = (id) => {
      data.editDialogInfo = true;
      data.editInfoID = id;
    };

    // 删除按钮
    const deleteItem = (id) => {
      // vue 2.0
      /*root.confirm({
          message: "确认删除当前信息，确认后将无法恢复！",
          type: 'warning',
      })*/
      if (!id) {
        root.$message.error("获取参数失败请重试");
        return false;
      }
      data.deleteInfoID.push(id);
      // 3.0
      confirm({
        message: "确认删除当前信息，确认后将无法恢复！",
        type: "warning",
        success: confirmDelete,
        fial: () => {
          data.deleteInfoID = [];
        }
      });
    };

    // 编辑详情
    const toDetails = (data) => {
      // 预存值
      // root.$store.commit('editinfodetails/SET_ID', data.id);
      // root.$store.commit('editinfodetails/SET_TITLE', data.title);
      root.$store.commit("editinfodetails/UPDATA_STATE_VALUE", {
        id: {
          value: data.id,
          session: true,
          sessionKey: "infoID"
        },
        title: {
          value: data.title,
          session: true,
          sessionKey: "infoTitle"
        }
      });
      root.$router.push({
        path: "InfoEditDetails"
      });
    };

    // 批量删除
    const delectAll = () => {
      // Vue2.0
      /*root.confirm({
          message: "确认删除选中的数据，确认后将无法恢复！",
          type: "warning",
          fn: confirmDelete,
          id: '111'
      });*/
      if (data.deleteInfoID.length === 0) {
        root.$message.error("请至少选择一条数据");
        return false;
      }
      // Vue3.0
      confirm({
        message: "确认删除选中的数据，确认后将无法恢复！",
        type: "warning",
        success: confirmDelete,
        fial: () => {
          data.deleteInfoID = [];
        }
      });
    };

    // 确认删除
    const confirmDelete = () => {
      DelectInfo({ id: data.deleteInfoID || [] }).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
          laodData();
          data.deleteInfoID = [];
        }
      }).catch(error => {
        console.log(error);
      });
    };

    const handleSizeChange = (val) => data.pageSize = val;
    // 选中页码
    const handleCurrentChange = (val) => {
      data.pageNum = val;
      laodData();
    };
    // 选中checkbox
    const handleSelectionChange = (val) => {
      let selectID = val.map(item => item.id);
      data.deleteInfoID = selectID;
    };
    /**
     *  生命周期
     */
    onMounted(() => {
      // 获取分类
      getInfoCategory(); // GetInfoCategory();
      // 获取列表
      laodData();
    });

    /**
     *  watch
     */
    watchEffect(() => categoryItem.data, (value) => {
      // TODO
      console.log(value);
      data.categoryData = value;
    });

    return {
      // reactive
      data,
      // 方法
      laodData, toCategory, toDate, deleteItem, handleEdit, delectAll, handleSizeChange, handleCurrentChange,
      handleSelectionChange, toDetails
    };
  }
};
</script>

<style scoped lang="scss">
@import "../../styles/config.scss";

.form_item {
  &.category {
    @include labelDom(left, 60, 40)
  }

  &.date {
    @include labelDom(right, 93, 40)
  }

  &.keyword {
    @include labelDom(right, 99, 40)
  }
}

.el-button + a {
  margin-left: 10px;
}
</style>
